﻿var Image = {
    model: function (d = {}) {
        this.Title = d.Title || "图片上传";
        this.EnTitle = d.EnTitle || "";
        this.Tips = d.Tips || "";
        this.Name = d.Name || 'lg' + lg.GetSN(6, 10);
        this.Value = d.Value || "";
        this.ExportName = d.ExportName || "";
        this.Width = d.Width || "100%";
        this.Required = d.Required || false;
        this.Api = d.Api || "";
        this.IsRender = d.IsRender != undefined ? d.IsRender : true;
        this.IsShow = d.IsShow || false;
        this.IsExport = d.IsExport || false;
        this.IsWhere = d.IsWhere || false;
        this.WhereKey = d.WhereKey || "精确匹配";
        this.MaxSize = d.MaxSize || 1;
        this.FileTypes = d.FileTypes || ['jpg', 'png'];
        this.FileCount = d.FileCount || 1;
    },
    component: {
        name: "lg-form-image",
        data: {
            props: {
                items: {
                    type: Array,
                    default: []
                },
                value: {
                    type: String,
                    default: ""
                },
                data: {
                    type: Object,
                    default: {}
                },
                requestParam: {
                    type: Object,
                    default: null
                },
                //0填写 1查看
                renderType: {
                    type: Number,
                    default: 0
                }
            },
            data() {
                return {
                    dataUrl: ""
                }
            },
            mounted: function () {

            },
            methods: {
                onSelect: function () {
                    if (this.renderType == 1) {
                        this.$emit("event", { "type": "file", "name": this.data.Name, "eventName": "load" });
                    } else {
                        console.log(this.$refs.fileSelector);
                        this.$refs.fileSelector.click();
                    }

                },
                onSelected: function () {
                    var that = this;
                    var file;
                    var files = this.$refs.fileSelector.files;
                    //校验文件数，未选择文件则不执行任何事件
                    if (files.length == 0) {
                        return false;
                    }
                    file = files[0];
                    if (window.FileReader) {
                        //FileReader读取图片dataUrl
                        const reader = new FileReader();
                        reader.readAsDataURL(file);
                        reader.onload = function (readRes) {
                            console.log(that.value);
                            that.dataUrl = readRes.target.result;
                        }
                        //主要逻辑
                        {
                            if ((file.size / 1024 / 1024).toFixed(2) > parseFloat(this.data.MaxSize)) {
                                layer.msg("文件尺寸超限！最大允许上传" + this.data.MaxSize + "M!");
                                return false;
                            }
                            if (this.data.FileTypes.filter(p => p == file.name.split('.').pop()).length == 0) {
                                layer.msg("文件类型不支持！允许的类型：" + JSON.stringify(this.data.FileTypes));
                                return false;
                            }
                            //上传
                            var fd = new FormData();
                            fd.append("file", file);
                            fd.append("name", this.data.Name);
                            if (this.requestParam != null) {
                                for (let key in this.requestParam) {
                                    fd.append(key, this.requestParam[key]);
                                }
                            }
                            lg.postFile({
                                url: this.data.Api,
                                data: fd,
                                success: res => {
                                    if (res.code == 0) {
                                        this.$emit("update:value", res.data);
                                    } else {
                                        layer.msg(res.msg, { icon: 2 })
                                    }
                                },
                                fail: res => {
                                    layer.msg("接口请求异常！", { icon: 2 })
                                }
                            })
                        }
                    } else {
                        layer.msg("您的浏览器不支持上传插件！", { icon: 2 })
                    }
                    this.$refs.fileSelector.value = '';
                },
                upFile: function (file) {
                    var fd = new FormData();
                    fd.append("file", file.file);
                    fd.append("name", this.data.Name);
                    if (this.requestParam != null) {
                        for (let key in this.requestParam) {
                            fd.append(key, this.requestParam[key]);
                        }
                    }
                    lg.postFile({
                        url: this.data.Api,
                        data: fd,
                        success: res => {
                            if (res.code == 0) {
                                file.state = "success";
                                file.progress = "100";
                                file.url = res.data;
                                this.setValue();
                            } else {
                                file.state = "fail";
                                file.progress = "100";
                                file.errMsg = res.msg;
                            }
                        },
                        fail: res => {
                            file.state = "fail";
                            file.progress = "100";
                            file.errMsg = "接口请求异常！";
                        }
                    })
                },
                remove: function (i) {
                    var that = this;
                    layer.confirm("确定要移除当前文件吗？", function (box) {
                        layer.close(box);
                        that.files.splice(i, 1);
                    })
                },
                setValue: function () {
                    var arr = this.files.filter(p => p.state == 'success');
                    var value = [];
                    if (arr.length > 0) {
                        for (let i in arr) {
                            value.push(arr[i].url)
                        }
                        this.$emit("update:value", value);
                    }
                },
                open: function (file) {
                    window.open(file.url, "_blank");
                }
            },
            template: `
<div :class="['lg-form-item','pane',{'lg-ver-error':data.error}]" :style="{'width':data.Width}">
	<div class="lg-form-block">
		<div class="lg-form-title">
			<div class="lg-form-title-item">
				<i v-if="data.Required">*</i>
				<span class="cn">{{data.Title}}</span>
				<span class="en">{{data.EnTitle}}</span>
			</div>
		</div>
		<input type="file" id="fileUp" class="hide" multiple ref='fileSelector' v-on:change="onSelected" />
		<div class="lg-form-control lg-upload lg-form-image-alone">
			<div class="lg-file-image-btn lg-image-item" v-on:click="onSelect">
				 <span class="fa fa-plus">点击上传图片</span>
				 <div class="img" v-if="value!=''"><img :src="dataUrl"></div>
			</div>
		</div>
	</div>
	<div class="lg-form-block">
		<div class="lg-form-tip">
			<p>{{data.Tips}}</p>
		</div>
		<div class="lg-form-ver" v-if="data.error">{{data.errMsg}}</div>
	</div>
</div>`
        }
    }
}

Image.model.prototype.verify = function () {
    var res = { state: true, msg: "ok" };
    if (this.Required) {

        if (this.Value.length == 0) {
            res.state = false;
            res.msg = "文件未上传!";
            return res;
        }
    }
    return res
}
Image.model.prototype.getValue = function () {
    if (typeof this.Value == 'object' && this.Value.length == 0) {
        return ""
    }
    return this.Value;
}
Image.model.prototype.setValue = function (data) {
    var val = data[this.Name];
    if (typeof val == "object") {
        this.Value = val;
    } else {
        this.Value = lg.convert.toJson(val, "");
    }
}

export { Image }